package com.ruoyi.nongjt.service.impl;

import com.ruoyi.nongjt.domain.User;
import com.ruoyi.nongjt.dto.ChangePasswordRequest;
import com.ruoyi.nongjt.dto.LoginRequest;
import com.ruoyi.nongjt.dto.RegisterRequest;
import com.ruoyi.nongjt.mapper.UserMapper;
import com.ruoyi.nongjt.service.UserService;
import com.ruoyi.nongjt.config.PasswordEncoder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private JavaMailSender mailSender;

    @Value("${spring.mail.username}")
    private String fromEmail;

    // 模拟存储验证码（生产环境应使用 Redis）
    private static final Map<String, CodeInfo> CODE_STORAGE = new HashMap<>();

    @Override
    public String register(RegisterRequest request) {
        if (!verifyCode(request.getEmail(), request.getCode())) {
            return "验证码错误或已过期";
        }

        User existing = userMapper.findByEmail(request.getEmail());
        if (existing != null) {
            return "该邮箱已被注册";
        }

        User user = new User();
        user.setEmail(request.getEmail());
        user.setPassword(PasswordEncoder.encode(request.getPassword()));
        user.setNickname("用户" + System.currentTimeMillis() % 10000);

        userMapper.insertUser(user);
        CODE_STORAGE.remove(request.getEmail()); // 注册成功删除验证码

        return "注册成功";
    }

    @Override
    public String login(LoginRequest request) {
        User user = userMapper.findByEmail(request.getEmail());
        if (user == null) {
            return "用户不存在";
        }
        if (!PasswordEncoder.matches(request.getPassword(), user.getPassword())) {
            return "密码错误";
        }
        return "登录成功";
    }

    @Override
    public void sendVerificationCode(String email) {
        String code = generateCode();
        LocalDateTime expiredAt = LocalDateTime.now().plusMinutes(5);

        // 发送邮件
        SimpleMailMessage message = new SimpleMailMessage();
        message.setFrom(fromEmail);
        message.setTo(email);
        message.setSubject("注册验证码");
        message.setText("您的注册验证码是：" + code + "，5分钟内有效。");

        mailSender.send(message);

        // 保存验证码
        CODE_STORAGE.put(email, new CodeInfo(code, expiredAt));
    }

    @Override
    public boolean verifyCode(String email, String code) {
        CodeInfo info = CODE_STORAGE.get(email);
        if (info == null) return false;
        if (!info.getCode().equals(code)) return false;
        if (info.getExpiredAt().isBefore(LocalDateTime.now())) {
            CODE_STORAGE.remove(email);
            return false;
        }
        return true;
    }

    private String generateCode() {
        Random r = new Random();
        return String.format("%06d", r.nextInt(1000000));
    }

    // 验证码信息类
    private static class CodeInfo {
        private String code;
        private LocalDateTime expiredAt;

        public CodeInfo(String code, LocalDateTime expiredAt) {
            this.code = code;
            this.expiredAt = expiredAt;
        }

        // getter
        public String getCode() { return code; }
        public LocalDateTime getExpiredAt() { return expiredAt; }
    }


    @Override
    public String changePassword(ChangePasswordRequest request) {
        // 验证验证码
        if (!verifyCode(request.getEmail(), request.getCode())) {
            return "验证码错误或已过期";
        }

        // 查找用户
        User user = userMapper.findByEmail(request.getEmail());
        if (user == null) {
            return "用户不存在";
        }

        // 更新密码
        user.setPassword(PasswordEncoder.encode(request.getNewPassword()));
        userMapper.updateUser(user);

        // 删除已使用的验证码
        CODE_STORAGE.remove(request.getEmail());

        return "密码修改成功";
    }

}
